package com.alimama.aop;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.alimama.dao.IBusinessLogDao;
import com.alimama.entity.BusinessLog;

@Aspect
@Component("logAspect")
public class LogAspect {

	private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);
	
	@Autowired
	private IBusinessLogDao businessLogDao;

	@Pointcut("@annotation(com.alimama.aop.BusAnnotion)")
	private void deal() {
	}


	@Around("deal()")
	public Object before(ProceedingJoinPoint joinPoint) {

		// 获取注解
		Signature signature = joinPoint.getSignature();
		MethodSignature methodSignature = (MethodSignature) signature;
		BusAnnotion busAnnotion = methodSignature.getMethod().getAnnotation(BusAnnotion.class);
		long startTime = System.currentTimeMillis();

		// 执行业务
		Object obj = null;
		try {
			obj = joinPoint.proceed();
		} catch (Throwable e) {
			logger.error(e.getMessage());
		}

		/**
		 * 日志记录
		 */
		long extend = System.currentTimeMillis() - startTime;
		try {
			Object[] args = joinPoint.getArgs();
			BusinessLog log = new BusinessLog();
			log.setBusinessType(busAnnotion.bussineType());
			log.setExpends(extend);
			log.setMethod(busAnnotion.method());
			log.setVersion(busAnnotion.version());
			log.setAccount((String) SecurityUtils.getSubject().getPrincipal());
			log.setRequsetContent((String)args[0]);
			log.setReponseContent(JSON.toJSONString(obj));
			log.setUrl(getRequest().getRequestURI().toString());
			log.setSrcIp(getIpAddr());
			log.setCode(200);
			businessLogDao.save(log);
		} catch (Exception e) {
			logger.error(e.getMessage());
		}
		return obj;
	}

	private HttpServletRequest getRequest() {
		RequestAttributes ra = RequestContextHolder.getRequestAttributes();
		ServletRequestAttributes sra = (ServletRequestAttributes) ra;
		HttpServletRequest httpServletRequest = sra.getRequest();
		return httpServletRequest;
	}

	/**
	 * 获取请求
	 * @return
	 */
	public String getIpAddr() {
		String ipAddress = null;
		HttpServletRequest request = getRequest();
		ipAddress = request.getHeader("x-forwarded-for");
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
		}

		// 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if (ipAddress != null && ipAddress.length() > 15) {
			if (ipAddress.indexOf(",") > 0) {
				ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}
}
